﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Infrastructure
{
    /// <summary>
    /// 
    /// </summary>
    public class TreeTableResultObject : TreeResultObjectBase<DataRow>
    {
        DataTable _flatDataTable;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="flatDataTable"></param>
        /// <param name="nodeKey"></param>
        /// <param name="superKey"></param>
        /// <param name="sortKey"></param>
        /// <param name="groupKey"></param>
        public TreeTableResultObject(DataTable flatDataTable, string nodeKey, string superKey, string sortKey, string groupKey) : base(flatDataTable.Rows.Count, nodeKey, superKey, sortKey, groupKey)
        {
            _flatDataTable = flatDataTable;
        }
        /// <summary>
        /// 
        /// </summary>
        protected DataTable FlatDataTable
        {
            get
            {
                return _flatDataTable;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="groupFlatData"></param>
        /// <returns></returns>
        protected override ITreeGroup CreateTreeGroup(object groupId, IEnumerable<DataRow> groupFlatData)
        {
            var dataTable = this.FlatDataTable.Clone();
            foreach (DataRow dataRow in groupFlatData)
            {
                dataTable.ImportRow(dataRow);
            }
            return new TreeTableGroup(groupId, this.NodeKey, this.SuperKey, this.SortKey, dataTable);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotSupportedException"></exception>
        protected override IEnumerable<IGrouping<object, DataRow>> GetGroups()
        {
            var dataRows = this.FlatDataTable.Select();
            var groups = dataRows.GroupBy(d => d[this.GroupKey]);
            return groups;
        }
    }
}
